<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="标准名称">
        <el-input
          v-model="queryParams.standardName"
          placeholder="请输入关键字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="关键字">
        <el-input v-model="queryParams.keyword" placeholder="请输入关键字" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>-->
      <el-form-item label="标准级别" prop="levelValue">
        <el-select v-model="queryParams.levelValue" placeholder="请选择标准级别" clearable>
          <el-option
            v-for="dict in dict.type.sys_standard_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标准领域" prop="domainValue">
        <el-select v-model="queryParams.domainValue" placeholder="请选择标准领域" clearable>
          <el-option
            v-for="dict in dict.type.sys_standard_area"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标准性质" prop="natureValue">
        <el-select v-model="queryParams.natureValue" placeholder="请选择标准性质" clearable>
          <el-option
            v-for="dict in dict.type.sys_standard_nature"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标准内容" prop="contentValue">
        <el-select v-model="queryParams.contentValue" placeholder="请选择标准内容" clearable>
          <el-option
            v-for="dict in dict.type.sys_standard_content"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="有效性" prop="effectValue">
        <el-select v-model="queryParams.effectValue" placeholder="请选择有效性" clearable>
          <el-option
            v-for="dict in dict.type.sys_availability_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="计量状态" prop="calculateValue">
        <el-select v-model="queryParams.calculateValue" placeholder="请选择计量状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_metering_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:standard:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:standard:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:standard:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:standard:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="printBox"
          v-hasPermi="['system:standard:print']"
        >打印</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" width="55">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>

      <el-table-column
        min-width="300"
        fixed
        label="标准名称"
        prop="standardName"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <el-link @click="handleDetailDiag(scope.row)" type="primary">
            {{
            scope.row.standardName
            }}
          </el-link>
        </template>
      </el-table-column>

      <el-table-column
        label="代号及年代号"
        prop="standardCode"
        :show-overflow-tooltip="true"
        width="140"
      />
      <el-table-column label="预览" prop="fileCode" :show-overflow-tooltip="true" width="60">
        <template slot-scope="scope" v-if="scope.row.fileUrl">
          <el-link
            type="primary"
            :href="baseUrl + item"
            target="_blank"
            v-for="item in scope.row.fileUrl.split(',')"
          >{{ getFileName(item) }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="实施日期" prop="executiveDate" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="替代情况" width="140" prop="replaceInfo" :show-overflow-tooltip="true" />
      <el-table-column label="标准级别" width="120" prop="levelName" :show-overflow-tooltip="true" />
      <el-table-column label="标准领域" width="120" prop="domainName" :show-overflow-tooltip="true" />
      <el-table-column label="标准性质" prop="natureName" :show-overflow-tooltip="true" />
      <el-table-column label="标准内容" prop="contentName" width="140" :show-overflow-tooltip="true" />
      <el-table-column label="有效性" width="140" prop="effectName" :show-overflow-tooltip="true" />
      <el-table-column label="计量状态" prop="calculateName" width="100" :show-overflow-tooltip="true" />
      <el-table-column label="宣贯日期" width="140" prop="publicityDate" :show-overflow-tooltip="true" />
      <el-table-column label="总数量" prop="totalNum" width="100" :show-overflow-tooltip="true" />
      <el-table-column label="当前库存数量" prop="currentNum" width="100" :show-overflow-tooltip="true" />

      <el-table-column
        label="操作"
        align="center"
        width="250"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" v-hasPermi="['system:file:ly']"
          @click="handleCode(scope.row)">二维码领用</el-button>-->
          <el-button
            size="mini"
            type="text"
            v-hasPermi="['system:standard:ff']"
            @click="handleSend(scope.row)"
          >平台领用</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            v-hasPermi="['system:standard:info']"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:standard:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:standard:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            v-hasPermi="['system:file:ly']"
            @click="handleFile(scope.row)"
          >附件二维码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 打印模板位置 -->
    <PrintBox
      :pageNum="queryParams.pageNum"
      :total="total"
      :printRow="printList"
      :checkNum="10"
      :checkLabel="'contentList'"
      id="printBox"
    >
      <template slot="title" slot-scope="scope">
        试验室受控文件清单 STET/B/03-8
        <div style="font-size: 14px; margin-top: 5px">
          <span v-if="zlcode.includes(Number(fileTypeValue))">
            （质量活动记录表格 （通用类、标定类、各类试验物质及设备验收类、
            辅助类、期间核查类）
          </span>

          <span v-if="wlwjcode.includes(Number(fileTypeValue))">(往来文件(本公司发文、上级单位来文、外单位来文))</span>
          <span v-if="[6, 15, 16].includes(Number(fileTypeValue))">(质量手册、资源手册、程序文件)</span>
          <span v-if="[7, 8, 10, 11, 12, 113, 14].includes(Number(fileTypeValue))">(作业指导书)</span>
          <span
            v-if="[23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34].includes(Number(fileTypeValue))"
          >(质量活动记录表格（原始观测数据、记录、检测报告）)</span>
          <span v-if="fileTypeValue == 22">(检测方法)</span>
        </div>
      </template>
      <template slot-scope="scope" style="position: relative;">
        <!-- <div style="position: absolute; top: 100px;left: 200px;">
          <img src="../../../assets/images/watermark.png" alt="" style="width: 200px;height: 80px;">
        </div>-->
        <!-- 表格  class  table-page  必须-->
        <table style="border-collapse: collapse" border="1" cellspacing="0" class="table-page">
          <thead>
            <tr class="table_header">
              <th style="width: 20mm">序号</th>
              <th style="width: 30mm">受控编号</th>
              <th style="width: 45mm">文件名</th>
              <th style="width: 65mm">文件类型</th>
              <th style="width: 55mm">文件状态</th>
              <th style="width: 50mm">文件废止日期</th>
              <th style="width: 50mm">文件实施日期</th>
              <th style="width: 50mm">备注</th>
              <!-- <th
                  style="width: 50mm"
                  v-if="wlwjcode.includes(Number(fileTypeValue))"
                >
                  文件下发日期
              </th>-->
            </tr>
          </thead>
          <!-- 同列表接口数据 -->
          <tbody>
            <tr v-for="(e, i) in 10">
              <td>{{ scope.item.contentList[i] ? i + 1 : "" }}</td>
              <td>
                {{
                (scope.item.contentList[i] &&
                scope.item.contentList[i].standardCode) ||
                ""
                }}
              </td>
              <td style="width: 45mm;">
                {{
                scope.item.contentList[i] &&
                scope.item.contentList[i].standardName
                }}
              </td>
              <td>
                {{
                scope.item.contentList[i] &&
                scope.item.contentList[i].natureName
                }}
              </td>
              <td>
                {{
                scope.item.contentList[i] &&
                scope.item.contentList[i].effectName
                }}
              </td>

              <td>
                {{
                scope.item.contentList[i] &&
                parseTime(scope.item.contentList[i].endDate, "{y}-{m}-{d}")
                }}
              </td>
              <td>
                {{
                scope.item.contentList[i] &&
                parseTime(scope.item.contentList[i].executiveDate, "{y}-{m}-{d}")
                }}
              </td>
              <td>
                {{
                scope.item.contentList[i] &&
                scope.item.contentList[i].replaceInfo
                }}
              </td>
              <!-- <td v-if="wlwjcode.includes(Number(fileTypeValue))">
                  {{
                    scope.item.contentList[i] &&
                    parseTime(scope.item.contentList[i].createTime, "{y}-{m}-{d}")
                  }}
              </td>-->
            </tr>
          </tbody>
        </table>
      </template>
    </PrintBox>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog :visible.sync="showCode" title="领用二维码" width="300px" append-to-body>
      <div style="text-align: center">
        <vue-qr :text="textUrl" :size="200"></vue-qr>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="showFile" title="附件二维码" width="300px" append-to-body>
      <div style="text-align: center">
        <vue-qr :text="fileTextUrl" :size="200"></vue-qr>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="showSend" title="领用" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- <el-form-item label="领用数量" prop="num">
          <el-input v-model="form.num" placeholder="请输入领用数量" clearable :style="{ width: '100%' }">
          </el-input>
        </el-form-item>-->
        <el-form-item label="文件类型" prop="typeValue">
          <el-select v-model="form.typeValue" collapse-tags :style="{ width: '100%' }">
            <el-option label="原件" :value="1" />
            <el-option label="复印件" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button size="mini" @click="showSend = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="saveSend">确 定</el-button>
      </template>
    </el-dialog>
    <Detail ref="Detail" :id="id"></Detail>
  </div>
</template>
<script>
import { listStandard, delStandard } from "@/api/system/standard.js";
import { standardGetAdd } from "@/api/system/standRecord.js";
import store from "@/store";
import printStyle from "@/utils/print.js";
import Detail from "./detail.vue";

export default {
  name: "standard",
  components: {
    Detail
  },
  dicts: [
    "sys_standard_level",
    "sys_standard_area",
    "sys_standard_nature",
    "sys_standard_content",
    "sys_metering_status",
    "sys_availability_type"
  ],
  data() {
    return {
      id: null,
      baseUrl: this.$VUE_APP_IMG_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      dataList: [],
      // 弹出层标题
      // 日期范围
      dateRange: [],
      // 数据范围选项
      queryParams: {
        pageNum: 1,
        keyword: undefined,
        levelValue: undefined,
        domainValue: undefined,
        contentValue: undefined,
        natureValue: undefined,
        calculateValue: undefined,
        effectValue: undefined,

        pageSize: 10
      },
      showCode: false,
      showFile: false,
      current: {},
      showSend: false,
      form: {
        num: 1
      },
      zlcode: [21, 20, 19, 18, 17], //质量活动记录表格
      wlwjcode: [2, 3, 4, 5], //外来文件
      rules: {
        typeValue: [
          {
            required: true,
            message: "请选择类型",
            trigger: "change"
          }
        ]
        // num: [
        //   {
        //     required: true,
        //     message: "输入数量",
        //     trigger: "blur",
        //   },
        // ],
      },
      textUrl: "",
      fileTextUrl: "",
      infos: [], //勾选的数据
      printList: []
    };
  },
  created() {
    const str = sessionStorage.getItem("queryParams");
    console.log(JSON.parse(str));
    if (str) {
      this.queryParams = JSON.parse(str);
      // this.queryParams.fileStatusValue=['1']
      // this.queryParams.fileTypeValue=['16']
      console.log(this.queryParams);

      setTimeout(() => {
        sessionStorage.removeItem("queryParams");
      }, 500);
    }
    this.getList();
  },
  methods: {
    handleprintArea(e) {
      // this.printItem = e
      this.textUrl =
        process.env.VUE_APP_CODE_API + "fileManager?id=" + e.fileManagerId;
      this.showCode = true;
    },
    printBox() {
      //infos  勾选的数据 如果有勾选就打印勾选。
      if (this.infos.length) {
        this.printList = [
          {
            contentList: this.infos
          }
        ];
      } else {
        //反之打印当前整个列表
        this.printList = [
          {
            contentList: this.dataList
          }
        ];
      }
      // 7, 8, 10, 11, 12, 113, 14
      // 6, 15, 16
      // zlcode
      // wlwjcode
      let flag = false;
      let e = this.printList[0].contentList[0].fileTypeValue;
      if ([7, 8, 10, 11, 12, 113, 14].includes(Number(e))) {
        flag = this.printList[0].contentList.some(
          e => ![7, 8, 10, 11, 12, 113, 14].includes(Number(e.fileTypeValue))
        );
      } else if ([6, 15, 16].includes(Number(e))) {
        flag = this.printList[0].contentList.some(
          e => ![6, 15, 16].includes(Number(e.fileTypeValue))
        );
      } else if (this.zlcode.includes(Number(e))) {
        flag = this.printList[0].contentList.some(
          e => !this.zlcode.includes(Number(e.fileTypeValue))
        );
      } else if (this.wlwjcode.includes(Number(e))) {
        flag = this.printList[0].contentList.some(
          e => !this.wlwjcode.includes(Number(e.fileTypeValue))
        );
      } else if (
        [23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34].includes(Number(e))
      ) {
        flag = this.printList[0].contentList.some(
          e =>
            ![23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34].includes(
              Number(e.fileTypeValue)
            )
        );
      }
      if (flag) {
        this.$modal.msgWarning("多选数据 请保持类型一致");
        return;
      }
      this.fileTypeValue = this.printList[0].contentList[0].fileTypeValue;

      setTimeout(() => {
        this.$print({
          printable: "printBox", //打印区域id
          type: "html", //打印类型是html
          scanStyles: false,
          targetStyles: ["*"],
          style: this.workStyle()
        });
      }, 500);
    },
    handleFile(res) {
      console.log(res);
      this.showFile = true;
      // this.fileTextUrl = process.env.VUE_APP_CODE_API + "fileUrl?url=" + res.fileUrl;
      // this.fileTextUrl ='https://boss.jsstet-oa.com'  + res.fileUrl;
      this.fileTextUrl =
        process.env.VUE_APP_CODE_API +
        "standardManager?id=" +
        res.standardManagerId +
        "&btn=" +
        1;
      console.log(this.fileTextUrl);
    },
    // 可以自定义样式  printStyle 是公共样式 切勿私自修改
    workStyle() {
      return `${printStyle}
        table,
        table tr th,
        table tr td {
          padding: 4px;
        }
        .desc{
        text-align: left; font-size: 12px; margin-top: 10px
      }
            .df {
                display: flex;
              }
      `;
    },
    handleCode(res) {
      console.log(res);
      if (res.effectName == "作废") {
        this.$confirm("该标准已作废，确定要领用吗?", "平台领用", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.form = {};
            this.textUrl =
              process.env.VUE_APP_CODE_API +
              "standardManager?id=" +
              res.standardManagerId;
            this.showCode = true;
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      } else {
        this.textUrl =
          process.env.VUE_APP_CODE_API +
          "standardManager?id=" +
          res.standardManagerId;
        this.showCode = true;
      }
    },
    changeUser(e) {
      this.form.user = e.nickName;
    },
    saveSend() {
      this.form.num = 1;
      this.$refs["form"].validate(valid => {
        if (valid) {
          (this.form.standardManagerId = this.current.standardManagerId),
            standardGetAdd(this.form).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess("操作成功");
                this.showSend = false;
                this.getList();
              } else {
                if (res.msg == "尚有未审核记录，不允许申请，谢谢") {
                  this.$modal.msgError("不可重复领用");
                } else {
                  this.$modal.msgError(res.msg);
                }
              }
            });
        }
      });
    },
    handleSend(e) {
      if (e.effectName == "作废") {
        this.$confirm("该标准已作废，确定要领用吗?", "平台领用", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.form = {};
            this.current = e;
            this.showSend = true;
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      } else {
        this.form = {};
        this.current = e;
        this.showSend = true;
      }
    },
    getList() {
      this.loading = true;
      listStandard(
        this.addDateRangeTime(this.queryParams, this.dateRange)
      ).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleDetail(row) {
      sessionStorage.setItem("queryParams", JSON.stringify(this.queryParams));

      this.$router.push(
        "./addStandard?isInfo=true&id=" + row.standardManagerId
      );
    },
    handleDetailDiag(e) {
      this.$refs.Detail.show(e.standardManagerId);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.standardManagerId);
      this.infos = selection;
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push("./addStandard");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const configId = row.standardManagerId || this.ids;
      sessionStorage.setItem("queryParams", JSON.stringify(this.queryParams));
      console.log(sessionStorage.getItem("pageNum"));
      this.$router.push("./addStandard?isEdit=true&id=" + configId);
    },
    // 获取文件名称
    getFileName(name) {
      return "预览";
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    handleExport() {
      this.download(
        "system/standardManager/export",
        {
          ...this.queryParams,
          ids: this.ids.toString() || ""
        },
        `标准记录表_${this.parseTime(new Date().getTime(), "{y}-{m}-{d}")}.xlsx`
      );
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.standardManagerId || this.ids;
      let name = this.checkRow(
        userIds,
        this.dataList,
        "standardManagerId",
        "DELETE",
        "standardName"
      );
      this.$modal
        .confirm('是否确认删除标准名称为"' + name + '"的数据项？')
        .then(function() {
          return delStandard(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    }
  }
};
</script>
